package org.example.task3;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;

public class CreateTable {
    public static Configuration configuration;
    public static Connection connection;
    public static Admin admin;

    public static void init(){//建立连接
        configuration = HBaseConfiguration.create();
        configuration.set("hbase.rootdir","hdfs://localhost:8020/hbase");
        try{
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    public static void close(){//关闭连接
        try{
            if(admin != null){
                admin.close();
            }
            if(connection != null){
                connection.close();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    public static void createTable(String tableName,String[] fields) throws IOException{
        init();
        TableName tablename = TableName.valueOf(tableName);//定义表名
        if(admin.tableExists(tablename)){
            System.out.println("table is exists!");
            admin.disableTable(tablename);
            admin.deleteTable(tablename);
        }
        TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(tablename);
        for(int i=0;i<fields.length;i++){
            ColumnFamilyDescriptor family = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(fields[i])).build();
            tableDescriptor.setColumnFamily(family);
        }
        admin.createTable(tableDescriptor.build());
        close();
    }
    public static void main(String[] args){
        String[] fields = {"id","score"};
        try{
            createTable("test",fields);
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
